package util;

import java.util.*;

import objects.Asteroid;

import main.Constants;

import structure.SObject;

public class Partition {
	private Vector[][] contents;
	private static final int X_DIVIDE = 100;
	private static final int Y_DIVIDE = 100;


	public Partition() {
		contents = new Vector[Constants.MAX_X/X_DIVIDE][Constants.MAX_Y/Y_DIVIDE];
		for(int i = 0; i < contents.length; i++) {
			for(int j = 0; j < contents.length; j++) {
				contents[i][j] = new Vector();
			}
		}
	}

	public void rebin() {
		Vector<SObject> allItems = new Vector<SObject>();
		for(int i = 0; i < contents.length; i++) {
			for(int j = 0; j < contents[0].length; j++) {
				allItems.addAll(contents[i][j]);
				contents[i][j] = new Vector();
			}
		}
		for(SObject s : allItems) {
			add(s);
		}
	}

	public void add(SObject s) {
		if((s.getX() / X_DIVIDE) > 0 && (s.getY() / Y_DIVIDE) > 0) {
			contents[(int) (s.getX() / X_DIVIDE)][(int) (s.getY() / Y_DIVIDE)].add(s);
		}
	}

	public void remove(SObject s) {
		contents[(int) (s.getX() / X_DIVIDE)][(int) (s.getY() / Y_DIVIDE)].remove(s);
	}

	public Vector<SObject> getObjects(double x, double y, double width, double height) {

		Vector<SObject> results = new Vector<SObject>();
		for(int i = Math.max((int) (x / X_DIVIDE), Constants.MIN_X); i <= Math.min((x + width) / X_DIVIDE, contents.length - 1); i++) {
			for(int j = Math.max((int) (y / Y_DIVIDE), Constants.MIN_Y); j <= Math.min((y + height) / Y_DIVIDE, contents[i].length - 1); j++) {
				for(int k = 0; k < contents[i][j].size(); k++) {
					SObject o = (SObject) contents[i][j].get(k);
					if(o.getX() > x && o.getY() > y && o.getX() < x + width && o.getY() < o.getY() + height) {
						results.add(o);
					}
				}
			}
		}
		return results;
	}
}


